<template>
  <div class="sync-practice">
    <template ref="headerRef">
      <HeaderComponent @type-change="submit" @search="($event) => params['title'] = $event" />
    </template>
    <div class="left">
      <cus-condition :node-list="nodeList" @submit="$refs.listRef.request($event)" />
    </div>
    <div class="right">
      <cus-list ref="listRef" :default="params" url="/tiku/paper/queryExercise" :auto-request="false" :hasPage="true">
        <template #avatar>
          <img src="/src/assets/test-paper/list-avatar.png" style="width: 86px" alt="点津问道标品">
        </template>
        <template #default="{ data }">
          <div class="cus_content">
            <h1>{{ data.title }}</h1>
            <p>{{ data.exerciseType === 1 ? '进门测' : data.exerciseType === 2 ? '过手练' : data.exerciseType === 3 ? '出门测' : '课堂巩固' }}</p>
            <p>班型：{{data.courseTypeName}}</p>
            <p>教材：{{data.bookVersionName}}</p>
            <p>更新时间：{{ moment(data.modifyTime).format("YYYY-MM-DD HH:mm") }}</p>
          </div>
        </template>
        <template #actions="{ data }">
          <div class="list__actions">
            <el-button type="text" @click="seeDetail(data)"><i class="iconfont iconsearch-eye-line" /><span>查看</span></el-button>
            <el-button type="text" @click="download(data)"><i class="iconfont icondayin" /><span>下载</span></el-button>
            <el-button type="text" @click="update(data)" v-if="!data.filePath"><i class="iconfont iconfile-edit-line" /><span>编辑</span></el-button>
            <el-button type="text" @click="updateAttribute(data)" v-else><i class="iconfont iconfile-edit-line" /><span>编辑</span></el-button>
            <el-popconfirm title="确定要删除此练习吗？" confirmButtonText='确定' cancelButtonText='取消' @confirm="remove(data.id)">
              <template #reference>
                <el-button type="text" v-permissions="'delete'"><i class="iconfont iconshanchu" /><span>删除</span></el-button>
              </template>
            </el-popconfirm>
          </div>
        </template>
      </cus-list>
    </div>
  </div>
</template>
<script lang="ts">
import { ref, onMounted, Ref } from 'vue'
import HeaderComponent from './components/header.vue'
import { ElMessage, ElLoading } from 'element-plus'
import moment from 'moment'
import $ from '$'
import DownloadComponent from '@/views/test-paper/components/download.vue';
import EditUpdatePracticeComponent from './components/edit-update-practice.vue';

export default {
  components: { HeaderComponent },
  setup () {
    let params: Ref<any>  = ref({})
    let nodeList = ref([
      { label: '类别', key: 'exerciseType' },
      { label: '年级', key: 'gradeId' },
      { label: '年份', key: 'year' },
      { label: '学期', key: 'season'},
      { label: '教材版本', key: 'teacherBookVersionId' },
      { label: '班型', key: 'courseTypeId' }
    ])
    const submit = (val) => params.value = {...params.value, ...val}
    let listRef = ref()
    let headerRef = ref();
    onMounted(() => {
      $.emitter.emit('effect', (subjectId) => { params.value.subjectId = subjectId })
      $.emitter.emit('slot', headerRef)
    })
    /* 监听新增试卷成功事件 */
    const addEventHandle = (e) => {update(e); listRef.value && listRef.value.request(params.value); }
    $.emitter.on('add-test-success', addEventHandle);

    const deletePractice = (id) => {
      $.http.post(`/admin/syncExercise/deleteById/${id}`).then(res => {
        res.result ? ElMessage.success('删除成功！') :  ElMessage.warning(res.msg)
        res.result && listRef.value.request(params.value)
      })
    }

    const update = (data, preview = false) => {
      window.open(`./#/test-paper-edit/${preview}/${data.id}/${true}`);
    }

    const seeDetail = (data) => {
      if (data.filePath) {
        const loading = ElLoading.service({ lock: true, background: 'rgba(255, 255, 255, .7)', text: '加载中...' })
        let src = `${$.utils.generatBasePath()}furl=${import.meta.env.VITE_APP_BASE_URL}${data.filePath}`;
        let closeBtn = $.element('div', {
          className: 'el-icon-close',
          style: { width: '36px', height: '36px', lineHeight: '36px', textAlign: 'center', background: '#fff', borderRadius: '50%', fontSize: '24px', position: 'fixed', top: '40px', right: '40px', zIndex: '10', cursor: 'pointer' },
          on: { click: () => { container.remove(); } }
        });
        let iframe = $.element('iframe', { attrs: { src, width: '100%', height: '100%' }, style: { background: '#f9f9f9' } });
        iframe.onload = loading.close;
        let container = $.element('div', {
          style: { width: '100%', height: '100%', position: 'absolute', top: '0', left: '0', zIndex: '9' },
        }, [ closeBtn, iframe ])
        document.body.appendChild(container);
      } else {
        update(data, true);
      }
    }

    const remove = async (id) => {
      let res = await $.http.post('/tiku/paper/deletePaper', { id });
      ElMessage[res.result ? 'success' : 'error'](res.result ? '删除成功' : res.msg);
      res.result && listRef.value.request(params.value);
    }
    const updateAttribute = async (data) => {
      await $.modal.create({ title: '编辑练习', width: 480, component: EditUpdatePracticeComponent, props: { data: $.clone(data) } });
      listRef.value.request(params.value)
    }
    const download = (data) => {
      //1:手动 2:智能 3:上传
      if (data.filePath) {
        window.open(`${$.utils.generatBasePath()}info=3&furl=${import.meta.env.VITE_APP_BASE_URL + data.filePath}`);
        $.http.post('/tiku/paper/countDownloadPaper', { paperId: data.id }).then(res => res.result && (data.downloadCount = res.json.downloadCount));
      } else {
        $.modal.create({
          title: '下载试卷',
          width: 640,
          component: DownloadComponent
        }).then((res: any) => {
          window.open(`${import.meta.env.VITE_APP_BASE_URL}/tiku/paper/downPaper?paperId=${ data.id }&type=${ res.type }&templateId=${ res.templateId }&fileType=${ res.fileType }`);
          data.downloadCount++;
        });
      }
    }
    return { headerRef, listRef, moment, deletePractice, params, nodeList, submit, seeDetail, update, remove, updateAttribute, download }
  }
}
</script>
<style lang="scss" scoped>
.sync-practice {
  background: #fff;
  border-radius: 6px;
  padding: 20px;
  height: 100%;
  overflow: auto;
  .list__actions {
    display: flex;
    .el-button {
      width: 60px;
      color: #382A74;
      font-weight: 550;
      &:not(:first-child) {
        margin-left: 30px;
      }
      &:hover {
        color: #72b22a;
      }
      i {
        display: block;
        margin-bottom: 12px;
        font-size: 24px;
      }
    }
  }
  .cus_content {
    h1 {
      margin-top: 3px;
      margin-bottom: 10px;
      line-height: 20px;
    }
    h2 {
      margin-bottom: 10px;
    }
    p {
      color: #77808D;
      font-size: 12px;
    }
    & > div {
      color: #77808D;
      font-size: 12px;
      line-height: 20px;
      span:first-child {
        display: inline-block;
        width: 114px;
      }
    }
  }
  .cus_tag {
    margin-right: 8px;
    padding: 3px 10px;
    color: #333;
    font-size: 12px;
    line-height: 20px;
    border-radius: 2px;
    background: rgba(250, 173, 20, .15);
  }
}
</style>
